package com.yang.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yang.demo.entity.*;
import com.yang.demo.service.IMenuRoleService;
import com.yang.demo.service.IMenuService;
import com.yang.demo.service.IRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "权限管理")
@RestController
@RequestMapping("systemctl/basic/permission")
public class PermissionController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IMenuRoleService menuRoleService;

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/updateMenuRole")
    public RespBean updateMenuRole(Integer rid,Integer[] mid){
        return menuRoleService.updateMenuRole(rid,mid);
    }

    @ApiOperation(value = "根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMenuIdByRid(@PathVariable("rid") Integer id){
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid",id))
                //将对象转换成菜单id
                .stream().map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation("查询所有菜单")
    @GetMapping(value = "/menus")
    public List<Menu> getAllMenus(){
        return menuService.getAllMenus();
    }

    @ApiOperation(value = "获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles(){
        return roleService.list();
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/")
    public RespBean addAllRoles(@RequestBody Role role){
        if (roleService.save(role)){
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    @ApiOperation(value = "更新角色")
    @PutMapping("/")
    public RespBean updateRoles(@RequestBody Role role){
        if (roleService.updateById(role)){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation(value = "删除角色")
    @DeleteMapping("/role/{id}")
    public RespBean deleteRole(@PathVariable("id") Integer id){
        if (roleService.removeById(id)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "批量删除角色")
    @DeleteMapping("/")
    public RespBean deleteRoles(Integer[] ids){
        if (roleService.removeByIds(Arrays.asList(ids))){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }


}